package cn.gs.serializable.serialize;

// @author gs
import cn.gs.serializable.entity.IEntity;
import cn.gs.serializable.entity.MapEntity;
import cn.gs.serializable.serialize.ISerialize;
import cn.gs.serializable.serialize.SerializeController;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class MapSerialize extends AGenericSerialize {

    private ISerialize skey = null, svalue = null;
    private Class<?> ckey = null, cvalue = null;

    private ISerialize serialize(ISerialize z, ISerialize ctrl) {
        return z == null ? ctrl : z;
    }

    public MapSerialize() {
    }

    public MapSerialize(ISerialize key, ISerialize value) {
        this.skey = key;
        this.svalue = value;
    }

    public MapSerialize(Class<?> key, Class<?> value) {
        this.ckey = key;
        this.cvalue = value;
    }

    @Override
    public <T> T toObj(cn.gs.serializable.serialize.ISerialize ctrl, IEntity from, Class<T> clazz) {
        if (!(from instanceof MapEntity) || (clazz != null && !Map.class.isAssignableFrom(clazz))) {
            return null;
        }
        T coll = create(clazz, new HashMap());
        Map<IEntity, IEntity> entities = ((MapEntity) from).getMap();
        if (entities.isEmpty()) {
            //no item should be convert.
            return coll;
        }
        if (coll == null || !(coll instanceof Map)) {
            return null;
        }
        Map c = (Map) coll;
        //convert and add items
        for (Entry<IEntity, IEntity> e : entities.entrySet()) {
            Object p = serialize(skey, ctrl).toObj(ctrl, e.getKey(), ckey);
            Object q = serialize(svalue, ctrl).toObj(ctrl, e.getValue(), cvalue);
            c.put(p, q);
        }
        return coll;
    }

    @Override
    public IEntity fromObj(ISerialize ctrl, Object o) {
        if (o != null && o instanceof Map) {
            Map c = (Map) o;
            Map<IEntity, IEntity> entities = new HashMap<IEntity, IEntity>(c.size());
            for (Iterator it = c.entrySet().iterator(); it.hasNext();) {
                Entry f = (Entry) it.next();
                IEntity p = serialize(skey, ctrl).fromObj(ctrl, f.getKey());
                IEntity q = serialize(svalue, ctrl).fromObj(ctrl, f.getValue());
                entities.put(p, q);
            }
            return new MapEntity(entities);
        }
        return null;
    }
}
